package handlers

import (
	"encoding/json"
	"fast-food-mgr/cache"
	"fast-food-mgr/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func FoodAdd(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var food []models.Food
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}

	var total int64
	models.DB.Model(&models.Food{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  food,
		"total": total,
	})
	return
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "自盾不能为空",
		})
		return
	}
	var food models.Food
	err := models.DB.Create(&food).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}
}
